//
//  RecommandGiftViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/7/29.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "RecommandQRCodeView.h"
#import "RecommandGiftViewController.h"

#import "ShareItemPopViewController.h"
#import <WXApi.h>
#import <Photos/Photos.h>

@interface RecommandGiftViewController ()

@property (nonatomic, strong) UIScrollView *BGScrollview;

//背景图片
@property (nonatomic, strong) UIImageView *BGImageView;

//推荐有礼
@property (nonatomic, strong) UIImageView *recommandGiftImageview;

//邀请好友，获得奖金
@property (nonatomic, strong) UILabel *memoLab;


@property (strong, nonatomic) RecommandQRCodeView *QRCodeView;


@property (strong, nonatomic) RecommandModel *recommandModel;

@end

@implementation RecommandGiftViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self prepareData];
    [self initView];
}

- (RecommandQRCodeView *)QRCodeView {
    if (!_QRCodeView) {
       _QRCodeView = [[NSBundle mainBundle]loadNibNamed:@"RecommandQRCodeView" owner:nil options:nil].firstObject;
    }
    return _QRCodeView;
}

- (void)prepareData {
    
    self.recommandModel = [[RecommandModel alloc] init];
    
    self.recommandModel.itemUserIconUrl = [TTUserModel sharedObject].userIconURL;
    self.recommandModel.itemUserName = [TTUserModel sharedObject].userName;
    self.recommandModel.itemRecommandCode = [TTUserModel sharedObject].recommandCode;
    self.recommandModel.itemQRCodeImageUrl = [TTUserModel sharedObject].userIconURL;
    
    self.recommandModel.share_imageUrl = [TTUserModel sharedObject].userIconURL;
    
    self.recommandModel.share_HtmlUrl = [NSString stringWithFormat:@"%@%@?id=%@",TT_Global_H5_Domain,TT_HTML_SHARE_GIFT,self.recommandModel.itemRecommandCode];
    
    self.recommandModel.share_title = [NSString stringWithFormat:@"%@邀请你来玩拍拍得利。拍中省钱,不中赚钱！",[TTUserModel sharedObject].userName];
    self.recommandModel.share_desc = @"在这里，真正的议价权属于每个平凡的人，让用户定价，竞拍，赋予电商全新的参与和竞技趣味。";
    
}

- (void)shareUrl {
    
    WXWebpageObject *webpageObject = [WXWebpageObject object];
    webpageObject.webpageUrl = self.recommandModel.share_HtmlUrl;
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = self.recommandModel.share_title;
    message.description = self.recommandModel.share_desc;
    [message setThumbImage:[UIImage imageNamed:@"loginLogo"]];
    
    message.mediaObject = webpageObject;
    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
    req.bText = NO;
    req.message = message;
    req.scene = WXSceneSession;
    [WXApi sendReq:req];
    
}

- (void)shareImage {
    
//    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
//    [filter setDefaults];
//    NSString *string = self.recommandModel.share_HtmlUrl; //加入二维码url
//    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
//    [filter setValue:data forKeyPath:@"inputMessage"];
//
//    CIImage *image = [filter outputImage];
//    CGAffineTransform transform = CGAffineTransformMakeScale(1.0f, 1.0f);
//    CIImage *output = [image imageByApplyingTransform: transform];
//    UIImage *newImage = [UIImage imageWithCIImage:output scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
//
//    NSData * imageData = UIImageJPEGRepresentation(newImage, 0.7);
//
//    WXImageObject *imageObject = [WXImageObject object];
//    imageObject.imageData = imageData;
//
//    WXMediaMessage *message = [WXMediaMessage message];
//    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"res5"
//                                                         ofType:@"jpg"];
//    message.thumbData = [NSData dataWithContentsOfFile:filePath];
//    message.mediaObject = imageObject;
//
//    SendMessageToWXReq *req = [[SendMessageToWXReq alloc] init];
//    req.bText = NO;
//    req.message = message;
//    req.scene = WXSceneTimeline;
//    [WXApi sendReq:req];
}

- (void)initView {
    
    self.title = @"我的推荐";
    self.view.backgroundColor = UIColorHex(0xD63E3D);
    
    [self.QRCodeView fillBGWithModel:self.recommandModel];
    
    WEAKSELF
    self.QRCodeView.shareActionBlock = ^{

//        [weakSelf saveImage];
        
        if ([WXApi isWXAppInstalled]) {
            
            [weakSelf shareUrl];
            
        } else {
            [weakSelf alert:@"未安装微信客户端，请使用二维码邀请徒弟"];
        }

    };
    
    [self.view addSubview:self.BGScrollview];
    [self.BGScrollview addSubview:self.BGImageView];
    [self.BGImageView addSubview:self.recommandGiftImageview];
    [self.BGImageView addSubview:self.memoLab];
    [self.BGImageView addSubview:self.QRCodeView];

    [self.BGScrollview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.bottom.mas_equalTo(0);
    }];
    
    [self.BGImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.mas_equalTo(0);
        make.width.mas_equalTo(TTScreenWidth);
        make.height.mas_equalTo(TTScreenHeight - kNavBarAndStatusBarHeight);
    }];
    
    [self.recommandGiftImageview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.top.mas_equalTo(18);
        make.height.mas_equalTo(50);
    }];
    
    [self.memoLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(0);
        make.height.mas_equalTo(20);
        make.top.mas_equalTo(self.recommandGiftImageview.mas_bottom).offset(10);
    }];
    
    CGFloat betweenW = 60 ;
    CGFloat toBottom = 140 ;
    if (IS_IPHONE_4_OR_LESS) {
        betweenW = 40;
        toBottom = 30;
    } else if (IS_IPHONE_5) {
        betweenW = 40;
        toBottom = 30;
    } else if (IS_IPHONE_6) {
        betweenW = 60;
        toBottom = 100;
    } else if (IS_IPHONE_6P) {
        betweenW = 70;
        toBottom = 140;
    } else {
        betweenW = 50;
        toBottom = 200;
    }
    
    [self.QRCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.memoLab.mas_bottom);
        make.left.mas_equalTo(betweenW);
        make.right.mas_equalTo(-betweenW);
        make.bottom.mas_equalTo(-toBottom);
    }];
    
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
}

- (UILabel *)memoLab {
    if (!_memoLab) {
        _memoLab = [[UILabel alloc] init];
        _memoLab.text = @"邀请好友，获得奖金";
        _memoLab.font = [UIFont systemFontOfSize:15];
        _memoLab.textColor = [UIColor whiteColor];
    }
    return _memoLab;
}

- (UIImageView *)recommandGiftImageview {
    
    if (!_recommandGiftImageview) {
        _recommandGiftImageview = [[UIImageView alloc] init];
        [_recommandGiftImageview setImage:[UIImage imageNamed:@"recommand_gift"]];
    }
    return _recommandGiftImageview;
}

- (UIScrollView *)BGScrollview {
    
    if (!_BGScrollview) {
        _BGScrollview = [[UIScrollView alloc] init];
        _BGScrollview.backgroundColor = UIColorHex(0xD63E3D);
        _BGScrollview.contentSize = CGSizeMake(TTScreenWidth, TTScreenHeight - kNavBarAndStatusBarHeight + 1);
    }
    return _BGScrollview;
}

- (UIImageView *)BGImageView {
    
    if (!_BGImageView) {
        _BGImageView = [[UIImageView alloc] init];
        [_BGImageView setImage:[UIImage imageNamed:@"recommandBG"]];
        _BGImageView.userInteractionEnabled = YES;
    }
    return _BGImageView;
}


- (void)saveImage {
    
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, 0, [[UIScreen mainScreen] scale]);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(viewImage, self, @selector(imageSavedToPhotosAlbum:didFinishSavingWithError:contextInfo:), nil);
}

- (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {

       [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            //写入图片到相册
            [PHAssetChangeRequest creationRequestForAssetFromImage:image];

        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            
            NSLog(@"success = %d, error = %@", success, error);
        }];
}

@end
